//
//  LGPatientCarePlanAddController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/9/19.
//

#import "LGPatientCarePlanAddController.h"
#import "LGCarePlanTaskReviewCell.h"
#import "LGCarePlanTaskOtherCell.h"
#import "LGCarePlanTaskHeadView.h"
#import "LGPickerViewMax.h"
#import "DatePickerView.h"
@interface LGPatientCarePlanAddController ()<UITableViewDelegate,UITableViewDataSource>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)NSArray *inspectArray;
/**   */
@property (nonatomic , strong)NSArray *evaArray;
/**   */
@property (nonatomic , strong)NSArray *typeArray;
/**   */
@property (nonatomic , copy)NSString *typeString;
/**   */
@property (nonatomic , copy)NSString *typeCode;
/**   */
@property (nonatomic , copy)NSString *selectDate;
/**   */
@property (nonatomic , copy)NSString *descContent;
/**   */
@property (nonatomic , copy)NSString *remarkContent;
/**   */
@property (nonatomic , strong)NSMutableArray *checkResult;
/**   */
@property (nonatomic , strong)NSMutableArray *evaResult;
/**   */
@property (nonatomic , strong)NSMutableDictionary *taskData;
/**   */
@property (nonatomic , assign)BOOL dataChanged;
@end

@implementation LGPatientCarePlanAddController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.typeString = @"";
    self.typeCode = @"";
    self.dataChanged = NO;
    self.taskid = (_taskid && _taskid.length>0)?_taskid:@"";
    self.patientid = (_patientid && _patientid.length>0)?_patientid:@"";
    self.navigationView.title = ([self.taskid integerValue]>0)?@"编辑任务":@"新增任务";
    [self.view addSubview:self.tableView];
    [self createBottomView:self.taskid];
//    [self requestExamsData];
    [self requestEvaData];
    [self requestData];
}

-(void)backButtonAction{
    if(self.dataChanged == YES){
        __weak typeof(self) weakSelf = self;
        [LGAlertTool alertWithTitle:@"放弃调整" content:@"确定放弃调整？" sureAction:^{
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.care_plan/oneTaskDetail" parameters:@{@"task_id":self.taskid,@"patientid":self.patientid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.inspectArray = returnData[@"check_data"];
            NSDictionary *tempDic = returnData[@"task_data"];
            self.taskid = LGNSString(tempDic[@"task_id"]);
            self.typeCode = LGNSString(tempDic[@"task_type"]);
            self.selectDate = LGNSString(tempDic[@"task_date"]);
            self.descContent = LGNSString(tempDic[@"task_desc"]);
            self.remarkContent = LGNSString(tempDic[@"task_remark"]);
            self.taskSource = LGNSString(tempDic[@"task_source"]);
            self.checkResult = [NSMutableArray arrayWithArray:tempDic[@"task_check"]];
            self.evaResult = [NSMutableArray arrayWithArray:tempDic[@"task_eva"]];
            self.typeArray = returnData[@"types_data"];
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)requestEvaData{
    [RequestUtil withPOST:@"/doctor/select/scalesSelect" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            self.evaArray = returnData;
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}



-(void)setTypeArray:(NSArray *)typeArray{
    _typeArray = typeArray;
    for (NSDictionary *tempDic in typeArray) {
        if([LGNSString(tempDic[@"task_type"]) isEqualToString:self.typeCode]){
            self.typeString = LGNSString(tempDic[@"task_type_name"]);
        }
    }
}

//选择类型
-(void)selectTypeAction{
    if([self.taskSource isEqualToString:@"3"]){
        [TooltipView showMessage:@"药球患者导入任务无法更改类型" offset:0];
        return;
    }
    NSMutableArray *pickArray = [NSMutableArray array];
    for (NSDictionary *tempDic in self.typeArray) {
        [pickArray addObject:LGNSString(tempDic[@"task_type_name"])];
    }
    LGPickerViewMax *pickerView = [[LGPickerViewMax alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.pickArry = @[pickArray];
    pickerView.selectStr = self.typeString;
    [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectPickIndexResult = ^(NSArray *resultArray, NSArray *indexArray) {
        weakSelf.dataChanged = YES;
        weakSelf.typeString = LGNSString(resultArray[0]);
        weakSelf.typeCode = LGNSString(weakSelf.typeArray[[indexArray[0] integerValue]][@"task_type"]);
        [weakSelf.tableView reloadData];
    };
}

//选择时间
-(void)selectDateAction{
    DatePickerView *pickerView = [[DatePickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    pickerView.currentDate = self.selectDate;
    [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
    __weak typeof(self) weakSelf = self;
    pickerView.selectDate = ^(NSString *date) {
        weakSelf.dataChanged = YES;
        weakSelf.selectDate = date;
        [weakSelf.tableView reloadData];
    };
}

//保存任务
-(void)saveDataRequest{
    if(self.typeCode.length == 0 || [self.typeCode integerValue] == 0){
        [TooltipView showMessage:@"请选择任务类型" offset:0];
        return;
    }
    if(self.selectDate.length == 0){
        [TooltipView showMessage:@"请选择时间" offset:0];
        return;
    }
    
//    for (NSDictionary *taskDic in self.taskArray) {
//        NSString *taskid = LGNSString(taskDic[@"task_id"]);
//        NSString *taskDate = LGNSString(taskDic[@"task_date"]);
//        if([taskDate isEqualToString:self.selectDate] && ![taskid isEqualToString:self.taskid]){
//            [LGAlertTool alertWithTitle:@"无法保存" content:[NSString stringWithFormat:@"已有重叠的照护计划 %@,无法保存",taskDate] sureAction:^{
//            }];
//            return;
//        }
//    }

    
    if([self.typeCode isEqualToString:@"1"]){
        if (self.checkResult.count == 0 && self.evaResult.count == 0) {
            [TooltipView showMessage:@"请选择检查或评估项目" offset:0];
        }else{
            //复诊复查
            NSDictionary *saveDic = @{@"patient_id":self.patientid,@"level_id":self.levelid,@"task_id":self.taskid,@"task_type":self.typeCode,@"task_date":self.selectDate,@"task_desc":@"",@"task_remark":@"",@"check_data":self.checkResult,@"eva_data":self.evaResult};
            [RequestUtil withPOST:@"/doctor/patient.care_plan/oneTaskSave" parameters:saveDic withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
                if(code == 200){
                    [TooltipView showMessage:@"保存成功" offset:0];
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [TooltipView showMessage:message offset:0];
                }
            } error:^(NSError *error) {
                
            }];
        }
    }else{
        //其他
        NSDictionary *saveDic = @{@"patient_id":self.patientid,@"level_id":self.levelid,@"task_id":self.taskid,@"task_type":self.typeCode,@"task_date":self.selectDate,@"task_desc":self.descContent,@"task_remark":self.remarkContent,@"task_check":@[],@"task_eva":@[]};
        [RequestUtil withPOST:@"/doctor/patient.care_plan/oneTaskSave" parameters:saveDic withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshMedicinBallData" object:nil];
                [TooltipView showMessage:@"保存成功" offset:0];
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            
        }];
    }
}

//删除任务
-(void)deleteTaskAction{
    if([self.taskSource isEqualToString:@"3"]){
        [TooltipView showMessage:@"药球患者导入任务无法删除" offset:0];
        return;
    }
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"删除任务" content:@"确定删除这项任务" sureAction:^{
        [RequestUtil withPOST:@"/doctor/patient.care_plan/careTaskDelete" parameters:@{@"task_id":weakSelf.taskid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [TooltipView showMessage:@"删除成功" offset:0];
                [weakSelf.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            
        }];
    }];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger count = ([self.typeCode integerValue]>0)?4:2;
    return count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section<2){
        return 0;
    }else if (section == 2 && [self.typeCode isEqualToString:@"1"]){
        //检查
        return self.inspectArray.count;
    }else if (section == 3 && [self.typeCode isEqualToString:@"1"]){
        //评估
        return self.evaArray.count;
    }else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if([self.typeCode isEqualToString:@"1"]){
        //复诊复查
        LGCarePlanTaskReviewCell *reviewCell = [tableView dequeueReusableCellWithIdentifier:@"reviewCell" forIndexPath:indexPath];
        reviewCell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *tempDic = (indexPath.section == 2)?self.inspectArray[indexPath.row]:self.evaArray[indexPath.row];
        reviewCell.title = (indexPath.section == 2)? LGNSString(tempDic[@"name"]):LGNSString(tempDic[@"title"]);
        NSString *code = (indexPath.section == 2)?LGNSString(tempDic[@"code"]):LGNSString(tempDic[@"value"]);
        if(indexPath.section == 2){
            reviewCell.isSelect = [self.checkResult containsObject:code]?YES:NO;
        }else{
            reviewCell.isSelect = [self.evaResult containsObject:@([code integerValue])]?YES:NO;
        }
        return reviewCell;
    }else{
        LGCarePlanTaskOtherCell *otherCell = [tableView dequeueReusableCellWithIdentifier:@"otherCell" forIndexPath:indexPath];
        otherCell.selectionStyle = UITableViewCellSelectionStyleNone;
        otherCell.content = (indexPath.section == 2)?self.descContent:self.remarkContent;
        __block NSInteger index = indexPath.section;
        __weak typeof(self) weakSelf = self;
        otherCell.inputContentChanged = ^(NSString * _Nonnull content) {
            weakSelf.dataChanged = YES;
            if(index == 2){
                weakSelf.descContent = content;
            }else{
                weakSelf.remarkContent = content;
            }
        };
        return otherCell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if([self.typeCode isEqualToString:@"1"]){
        NSDictionary *tempDic = (indexPath.section == 2)?self.inspectArray[indexPath.row]:self.evaArray[indexPath.row];
        NSString *code = (indexPath.section == 2)?LGNSString(tempDic[@"code"]):LGNSString(tempDic[@"value"]);
        if(indexPath.section == 2){
            if([self.checkResult containsObject:code]){
                [self.checkResult removeObject:code];
            }else{
                [self.checkResult addObject:code];
            }
        }else{
            if([self.evaResult containsObject:@([code integerValue])]){
                [self.evaResult removeObject:@([code integerValue])];
            }else{
                [self.evaResult addObject:@([code integerValue])];
            }
        }
        [self.tableView reloadData];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return (section<2 || ![self.typeCode isEqualToString:@"1"])?viewPix(46):viewPix(56);
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = (section<2 || ![self.typeCode isEqualToString:@"1"])?viewPix(46):viewPix(56);
    NSArray *titleArray = [self.typeCode isEqualToString:@"1"]?@[@"类型",@"时间",@"检查",@"评估"]:@[@"类型",@"时间",@"描述",@"备注"];
    LGCarePlanTaskHeadView *headView = [[LGCarePlanTaskHeadView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    headView.title = titleArray[section];
    headView.subTitle = @"";
    if(section == 0){
        headView.showTip = YES;
        headView.content = self.typeString;
        [headView.actionBtn addTarget:self action:@selector(selectTypeAction) forControlEvents:UIControlEventTouchUpInside];
    }else if (section == 1){
        headView.showTip = YES;
        headView.content = self.selectDate;
        [headView.actionBtn addTarget:self action:@selector(selectDateAction) forControlEvents:UIControlEventTouchUpInside];
    }else{
        headView.showTip = NO;
        headView.content = @"";
        if(![self.typeCode isEqualToString:@"1"]){
            headView.subTitle = (section == 2)?@"(患者端可见)":@"(仅医生端可见)";
        }
    }
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return viewPix(15);
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    LGCornerFooterView *footView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(15))];
    footView.backgroundColor = [UIColor clearColor];
    footView.shadowView.cornerRidus = 12;
    footView.bottomMargin = viewPix(8);
    return footView;
}

-(NSMutableArray *)checkResult{
    if(!_checkResult){
        _checkResult = [NSMutableArray array];
    }
    return _checkResult;
}

-(NSMutableArray *)evaResult{
    if(!_evaResult){
        _evaResult = [NSMutableArray array];
    }
    return _evaResult;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topBarHeight, Screen_W, Screen_H-topBarHeight-viewPix(60)-bottomSafeBarHeight/3.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGCarePlanTaskReviewCell class] forCellReuseIdentifier:@"reviewCell"];
        [_tableView registerClass:[LGCarePlanTaskOtherCell class] forCellReuseIdentifier:@"otherCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}

-(void)createBottomView:(NSString *)taskid{
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(60)+bottomSafeBarHeight/3.0)];
    bottomView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomView];
    if([taskid integerValue]>0){
        //编辑
        UIButton *deleteBtn = [UIButton buttonWithTitle:@"删除" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#B3261E" selectColor:@"#B3261E"];
        deleteBtn.frame = CGRectMake(viewPix(16), viewPix(8), (Screen_W-viewPix(44))/2.0, viewPix(43));
        deleteBtn.layer.borderColor = [UIColor colorWithString:@"#DD3030"].CGColor;
        deleteBtn.layer.borderWidth = 1;
        deleteBtn.cornerRidus = 10;
        [deleteBtn addTarget:self action:@selector(deleteTaskAction) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:deleteBtn];
        
        UIButton *saveBtn = [UIButton buttonWithTitle:@"保存" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
        saveBtn.frame = CGRectMake(kMaxX(deleteBtn.frame)+viewPix(12), viewPix(8), (Screen_W-viewPix(44))/2.0, viewPix(46));
        saveBtn.backgroundColor = [UIColor colorWithString:@"#429BFF"];
        saveBtn.cornerRidus = 10;
        [saveBtn addTarget:self action:@selector(saveDataRequest) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:saveBtn];
    }else{
        //新增
        UIButton *saveBtn = [UIButton buttonWithTitle:@"保存" topMargin:viewPix(8)];
        [saveBtn addTarget:self action:@selector(saveDataRequest) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:saveBtn];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
